JavaScript Notes and Comparisons

Nexmoe October 20, 2023
This article is an AI translation and may contain semantic inaccuracies.

What does static mean in a JS class?

I was reading docs about the static property in JavaScript classes. The English version was hard to understand, and the Chinese version was also unclear.

English

We can also assign a method to the class as a whole. Such methods are called static.

Chinese

我们可以把一个方法作为一个整体赋值给类。这样的方法被称为 静态的(static)。

The idea is actually simple. In JavaScript, static is a keyword for defining static methods or static properties. Static methods/properties belong to the class itself, not an instance. That means you can call them directly on the class without instantiating it.

Static methods are attached to the class, not instances. They’re usually used for class‑level operations that don’t depend on instance state. You define them with the static keyword, for example:

class MyClass {
  static staticMethod() {
    console.log('This is a static method');
  }
}

MyClass.staticMethod(); // call the static method

In the example above, staticMethod() is called directly on the class MyClass without creating an instance. Static methods are not inherited by instances; they are called only on the class itself.

Static properties are also defined with static. They’re shared properties on the class, not on instances. For example:

class MyClass {
  static staticProperty = 'This is a static property';
}

console.log(MyClass.staticProperty); // access static property

Here, staticProperty is a static property and can be accessed via the class MyClass. It is not available on instances.

References

  1. Static properties and methods
  2. 静态属性和静态方法

[Comparison] type vs interface

In TypeScript, type and interface are both used to define types, but they have differences.

Similarities

  • Both can define objects, functions, union types, etc.
  • Both can be extended (extends) by other types.

Differences

Summary

  • In general, use interface if possible, because it’s easier to extend and has better hints [2]. It’s suitable for object shapes and declaration merging scenarios.
  • If you need complex types or need to use typeof to get instance types for assignment, use type [2].

Other

  • Tuple types are a special data type in TypeScript. Unlike normal arrays, each element in a tuple can have a different type.

References

  1. TypeScript 中 type 和 interface 有什么区别? - 知乎
  2. Typescript 中的 interface 和 type 到底有什么区别 - 掘金
  3. TS 篇-type 和 interface 的区别 - 掘金
  4. type 与 interface 的区别,你真的懂了吗? - 掘金
  5. 元组 · TypeScript 入门教程

[Summary] JavaScript variable scope and closures

  1. Lexical Environment
  • Every running function, code block, or script has an associated Lexical Environment object that stores local variables and function declarations.
  • A Lexical Environment has two parts: an Environment Record (stores variables) and a reference to the outer Lexical Environment.
  • When a function executes, it creates an inner Lexical Environment for its local variables and parameters.
  1. Variables
  • Variables are actually properties on the Lexical Environment. Reading/modifying variables means reading/modifying these properties.
  • Function declarations are initialized immediately, but let/const variables can only be read after declaration.
  • Block scope: variables declared inside {} are only visible within that block.
  1. Nested functions
  • Nested functions can access variables from outer functions, allowing them to encapsulate external variables.
  • Nested functions remember where they were created via the Environment reference, so they can always access external variables from that location.
  1. Closures
  • A closure is a function that remembers and can access external variables.
  • In JavaScript, all functions are naturally closures via the Environment reference.
  1. Garbage collection
  • If a nested function is referenced, the outer Lexical Environment won’t be collected.
  • If outer variables aren’t used by the nested function, engines may optimize them away so they can’t be accessed.
  1. Other
  • Understanding Lexical Environment and closures helps you write better JavaScript.
  • Nested functions and closures are useful for organizing code and encapsulating variables.
  • Variable optimization can make debugging harder.

[Summary] Notes on using async/await

  1. When using await, it’s best to wrap it in try...catch or use .catch() to handle rejections.
  2. If multiple awaited async operations are independent, trigger them in parallel with Promise.all() or by assigning to multiple variables.
  3. await can only be used inside an async function. Using await in a normal function will throw. If you use await in a normal function, it might run concurrently instead of sequentially; the correct approach is for loops or reduce().
  4. async functions preserve the call stack and don’t interrupt function execution, so you can keep error stack traces intact while async tasks run.

[Comparison] Iteration syntax

  • The most basic way to iterate is for, but it’s verbose.
  • Arrays provide forEach, which simplifies iteration but can’t break early.
  • for...in iterates array keys, but has downsides: keys are strings, it iterates manually added keys and prototype keys, and order isn’t guaranteed.
  • for...of is a newer syntax with advantages:
    • Simple syntax similar to for...in.
    • Unlike forEach, it allows break, continue, and return.
    • Provides a unified interface for iterating data structures.

for...of makes array iteration more convenient, while offering flexible control and a unified interface.